<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\ProductAttr;
use App\Models\ProductAttrResult;
use App\Models\ProductAttrValue;
use App\Models\StoreBargain;
use App\Traits\Controllers\AdminTraits;
use App\Traits\Controllers\UpdateStatusTraits;
use App\Transformers\Store\StoreBargainTransformer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class StoreBargainController extends Controller
{
    use AdminTraits;

    public $model = StoreBargain::class;

    public $transformer = StoreBargainTransformer::class;

    /**
     * 参数验证规则
     *
     * @param Request $request
     * @return array
     */
    public function rules(Request $request): array
    {
        switch ($request->method()) {
            case 'GET':
                return [];
                break;
            case 'POST':
            case 'PUT':
                return [

                    'pic' => 'required|max:255',
                    'rotation_chart' => 'required|array',
                    'title' => 'required|max:255',
                    'introduction' => 'required|max:255',
                    'start_at' => 'required',
                    'stop_at' => 'required',
                    'participants' => 'required',
                    'product_id' => 'required',
                    'people_num' => 'required',
                    'quota' => 'required',
                    'temp_id' => 'required',
                    'min_price' => 'required',
                    'desc' => 'required',
                    'shop_id' => 'required',
                    'attr_v' => 'required|array',

                ];
                break;
            case 'PATCH':
                return [];
                break;
        }
        return [];
    }

    /**
     * 验证信息
     *
     * @return array
     */
    public function ruleMessages(): array
    {
        return [
            'pic.required' => '主图不能为空',
            'product_id.required' => '商品ID不能为空',
            'rotation_chart.required' => '轮播图不能为空',
            'title.required' => '砍价活动名称不能为空',
            'min_price.required' => '砍价最低金额不能为空',
            'introduction.required' => '简介不能为空',
            'start_at.required' => '开始时间不能为空',
            'stop_at.required' => '结束时间不能为空',
            'participants.required' => '砍价人数不能为空',
            'people_num.required' => '帮砍次数不能为空',
            'quota.required' => '购买数量限制不能为空',
            'unit_name.required' => '单位名称不能为空',
            'temp_id.required' => '运费模板不能为空',
            'desc.required' => '详情内容不能为空',
            'shop_id.required' => '店铺不能为空',
            'attr_v.required' => '规格值必填',
            'attr_v.array' => '规格值必须为数组',

        ];
    }


    /**
     * 添加砍价商品
     *
     */
    public function store(Request $request)
    {

        $this->validateData($request);
        //判断如果没传商品ID 返回错误信息请选择商品信息
        $request->offsetSet('system_admin_id', $this->admin_user('id'));
        //判断如果开始时间比当前时间要早则不能添加
        if ($request->start_at < date('Y-m-d H:i:s')) return $this->response->errorBadRequest('时间比当前时间早');

        try {
            DB::beginTransaction();//开启事务

            //然后遍历规格数据拿到值
            $attr_v = [];
            $attr_r = [];
            foreach ($request->attr_v as $k => $v) {
                $attr_result['product_id'] = $request->product_id;
                $attr_result['result'] = $v;
                $attr_result['type'] = 'bargain';
                $attr_result['created_at'] = date('Y-m-d H:i:s');
                $attr_result['updated_at'] = date('Y-m-d H:i:s');
                $attr_r = $attr_result;//保存最新数据
                $attr_v = $v['value'][0];//获取值保存住
            }

            //判断砍价金额和限量是不是为空或者为零
            if (empty($attr_v['price']) || $attr_v['price'] == 0) return $this->response->errorBadRequest('砍价金额不能为空 或者小于等于零');
            if (empty($attr_v['quota']) || $attr_v['quota'] == 0) return $this->response->errorBadRequest('砍价限量不能为空 或者小于等于零');

            //2.把砍价价格和限量追加$request验证中,把数据也添加到本表中
            request()->offsetSet('price', $attr_v['price'],);//以属性的价格写到砍价表砍价金额中
            request()->offsetSet('quota_show', $attr_v['quota']);//以属性的限量写到砍价表砍价限量中
            request()->offsetSet('cost_price', $attr_v['cost']);//以属性的成本价写到砍价表砍价成本价中
            request()->offsetSet('stock', $attr_v['stock']);//以属性的库存写到砍价表砍价库存中
            request()->offsetSet('weight', $attr_v['weight']);//以属性的重量写到砍价表砍价重量中
            request()->offsetSet('volume', $attr_v['volume']);//以属性的体积写到砍价表砍价体积中

            //然后添加砍价规格的信息
            $this->getQuery()->attrResult()->insert($attr_r);
            $model = $this->getQuery()->fill($request->all());//添加砍价表信息
            $model->save();

            DB::commit();//提交事务
        } catch (\Exception $e) {
            DB::rollBack();//回滚事务
            report($e);
        }

        //进行批量赋值
        return $this->response->created();

    }

    /**
     * 修改砍价商品
     */
    public function update($id, Request $request)
    {
        $this->validateData($request);
        $request->offsetSet('system_admin_id', $this->admin_user('id'));
        $data = $this->getQuery()->findOrFail($id);

        try {
            DB::beginTransaction();//开启事务

            //然后遍历规格数据拿到值
            $attr_v = [];
            $attr_r = [];
            foreach ($request->attr_v as $k => $v) {
                $attr_result['product_id'] = $request->product_id;
                $attr_result['result'] = json_encode($v);
                $attr_result['type'] = 'bargain';
                $attr_result['created_at'] = date('Y-m-d H:i:s');
                $attr_result['updated_at'] = date('Y-m-d H:i:s');
                $attr_r = $attr_result;//保存最新数据
                $attr_v = $v['value'][0];//获取值保存住
            }
            //判断砍价金额和限量是不是为空或者为零
            if (empty($attr_v['price']) || $attr_v['price'] == 0) return $this->response->errorBadRequest('砍价金额不能为空 或者小于等于零');
            if (empty($attr_v['quota']) || $attr_v['quota'] == 0) return $this->response->errorBadRequest('砍价限量不能为空 或者小于等于零');

            //2.把砍价价格和限量追加$request验证中,把数据也添加到本表中
            request()->offsetSet('price', $attr_v['price'],);//以属性的价格写到砍价表砍价金额中
            request()->offsetSet('quota_show', $attr_v['quota']);//以属性的限量写到砍价表砍价限量中
            request()->offsetSet('cost_price', $attr_v['cost']);//以属性的成本价写到砍价表砍价成本价中
            request()->offsetSet('stock', $attr_v['stock']);//以属性的库存写到砍价表砍价库存中
            request()->offsetSet('weight', $attr_v['weight']);//以属性的重量写到砍价表砍价重量中
            request()->offsetSet('volume', $attr_v['volume']);//以属性的体积写到砍价表砍价体积中

            //执行修改
            $this->getQuery()->find($id)->attrResult()->where('type', 'bargain')->update($attr_r);
            $data->fill($request->all());
            $data->save();

            DB::commit();//提交事务
        } catch (\Exception $e) {
            DB::rollBack();//回滚事务
            report($e);
        }

        return $this->response->noContent();

    }

    /**
     * 删除砍价商品
     */
    public function destroy($id)
    {
        $ids = array_filter(explode(',', $id));
        if (empty($ids)) {
            return $this->response->errorBadRequest();
        }
        $data = $this->getQuery()->where('id', $id)->first();
        $data->attrResult()->where('product_id', $data->product_id)->where('type', 'bargain')->delete();
        $this->getQuery()->whereIn($this->getQuery()->getKeyName(), $ids)->delete();
        return $this->response->noContent();
    }

    /**
     * 砍价详情
     */
    public function show($id)
    {

        $show = $this->getQuery()->findOrFail($id);// findOrFail 查找失败时抛出异常404
        $show_r = $show->attrResult()->where('product_id', $show->product_id)->where('type', 'bargain')->first();
        $show->att_r = $show_r;
        if ($this->policy) {
            $this->authorize('show', $show);
            // authorize 控制器授权  当你尝试授权一个动作并且在用户不允许执行给定动作时抛出授权异常
            //那么使用authorize()方法，会在异常时返回一个异常403响应错误。
        }
        return $this->response->item($show, resolve($this->transformer));
    }

    /**
     * 是否上架
     */
    public function status(StoreBargain $storeBargain)
    {
        $storeBargain->status = $storeBargain->status == 0 ? 1 : 0;
        $storeBargain->save();
        $this->response->noContent();
    }
}

